//
//  BasicNavigationController.h
//  Binfen
//
//  Created by NigasMone on 14-12-1.
//  Copyright (c) 2014年 NigasMone. All rights reserved.
//

#import "ResetPasswordViewController.h"
#import "KWAlertView.h"
#import "TextInput.h"
#import "UITextField+Shake.h"
#import "StRequest.h"
@interface ResetPasswordViewController () {
    IBOutlet UIScrollView *contentScroller;
    
    IBOutlet KTextField         * phoneField;
    
    IBOutlet KTextField     * codeLabel;
    IBOutlet UIButton       * btngetCode;
    
    IBOutlet KTextField     * newPasswordLabel;
    IBOutlet KTextField     * newPasswordTwoLabel;

    IBOutlet UIButton           * btnSend;
    NSTimer                 * timer;
}
@property (nonatomic, assign) int time;
@end

@implementation ResetPasswordViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"找回密码";

    [self setEdgesNone];
    [btnSend infoStyle];
    currentInputView = phoneField;
    [phoneField infoStyle];
    
    [newPasswordLabel infoStyle];
    newPasswordLabel.tag=3;
    [newPasswordTwoLabel infoStyle];
    newPasswordLabel.tag=4;
    [codeLabel infoStyle];
    [btngetCode infoStyle];
    [btngetCode infoStyle];
    btngetCode.titleLabel.font = [UIFont systemFontOfSize:13];
    
    contentScroller.delegate = (id)self;
    [contentScroller setContentSize:CGSizeMake(0, [[UIScreen mainScreen] bounds].size.height-59)];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (timer) {
        // 强制停止计时器
        [timer invalidate];
        timer = nil;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
        __block BaseViewController *blockSelf = self;
        [blockSelf.view addKeyboardPanningWithActionHandler:^(CGRect keyboardFrameInView, BOOL opening, BOOL closing) {
            if (opening) {
                if (currentInputView.tag >3) {
                    // 有必要的时候 适应键盘
                    CGFloat oy = keyboardFrameInView.origin.y;
              
                        [contentScroller setContentInset:UIEdgeInsetsMake(0, 0, abs(currentInputView.bottom-oy)*2, 0)];
                  
                
                }
            }
            if (closing) {
                [contentScroller setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
                
            }
        }];
}
- (IBAction)send:(id)sender {
    [phoneField resignFirstResponder];
    if (phoneField.text.length != 11 ) {
        [self showText:@"请输入正确的手机号"];
        [phoneField shakeAlert];
    } else if (codeLabel.text.length == 0 ) {
        [self showText:@"请输入验证码"];
        [codeLabel shakeAlert];
    }
    else if (newPasswordLabel.text.length == 0 ) {
        [self showText:@"请输入新密码"];
        [newPasswordLabel shakeAlert];
    }
    else if (![newPasswordTwoLabel.text isEqualToString:newPasswordLabel.text]) {
        [self showText:@"两次密码输入不一致"];
        [newPasswordLabel shakeAlert];
        [newPasswordLabel shakeAlert];
    }
    else
    {
        // 提供接口后 请取消注释
        [super startRequest];
//        [client findPassword:phoneField.text];
        NSMutableDictionary * params = [NSMutableDictionary dictionary];
        [params setObject:phoneField.text forKey:@"phone"];
        [params setObject:codeLabel.text forKey:@"code"];
        [params setObject:newPasswordLabel.text forKey:@"password"];
        
        [client requestFor:params methodName:@"/user/apiother/editPassword"];
    }
}
- (BOOL)requestDidFinish:(BSClient*)sender obj:(NSDictionary*)obj {
    if ([super requestDidFinish:sender obj:obj]) {
//        NSDictionary *dic = [obj getDictionaryForKey:@"data"];
//        User * user = [User objWithJsonDic:dic];
//
//        [[BSEngine currentEngine] setCurrentUser:user password:newPasswordTwoLabel.text];
//        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//        [defaults setObject:phoneField.text forKey:KBSLoginUserName];
//        [defaults setObject:newPasswordTwoLabel.text forKey:KBSLoginPassWord];
//        [defaults synchronize];
//        
//        [self.navigationController popToRootViewControllerAnimated:YES];
        
        if(sender.hasError == NO)
        {
           [self.navigationController popToRootViewControllerAnimated:YES];
            return YES;
        }
        
    }
    return YES;
}

- (IBAction)btnGetCode:(UIButton*)sender {
    if (phoneField.text.length != 11) {
        [self showText:@"请输入正确的手机号"];
    } else {
        if (client) {
            return;
        }
        [self setLoading:YES content:@"正在发送验证码"];
        client = [[BSClient alloc] initWithDelegate:self action:@selector(requestDidCodeFinish:obj:)];
        [client getPhoneCode:phoneField.text];
        [self resignAllKeyboard:self.view];
    }
}
- (BOOL)requestDidCodeFinish:(id)sender obj:(NSDictionary *)obj {
    if ([super requestDidFinish:sender obj:obj]) {
        //        NSDictionary * data = [obj getDictionaryForKey:@"data"];
        //        NSString * code = [data getStringValueForKey:@"code" defaultValue:@""];
        [self showAlert:@"验证码已经发送到你的手机，请注意查收！" isNeedCancel:NO];
        //        codeLabel.text = code;
        btngetCode.enabled = NO;
        if (timer) {
            [timer invalidate];
            timer = nil;
        }
        _time = 60;
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(repeat:) userInfo:nil repeats:YES];
        [self repeat:nil];
    }
    return YES;
}
/**
 *	Copyright © 2014 Xizue Inc. All rights reserved.
 *
 *	刷新[获取验证码] 按钮的计数
 *
 *	@param 	tr 	计时器对象
 */
- (void)repeat:(NSTimer*)tr
{
    if (_time <= 0) {
        btngetCode.enabled = YES;
        [btngetCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        if (timer) {
            [timer invalidate];
            timer = nil;
        }
    } else {
        [btngetCode setTitle:[NSString stringWithFormat:@"剩余%d秒", _time] forState:UIControlStateDisabled];
        _time -= 1;
    }
}


- (void)kwAlertView:(KWAlertView*)sender didDismissWithButtonIndex:(NSInteger)index {
//    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
    
}

@end
